<template>
    <div>
        <el-dialog :title="dataTitle" v-model="dataOpen" width="810" append-to-body
                   :before-close="beforeChoose">
    <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="40px">
        <el-form-item label="名称" prop="number">
            <el-input
                v-model="queryParams.name"
                placeholder="请输入名称"
                style="width: 100px"
                @keyup.enter="handleQueryStu"
            />
        </el-form-item>
        <!--                @click="$refs.fileInput.click(ancestors)"-->

        <el-form-item>
            <el-button type="primary" plain icon="plus" :disabled="multiple" @click="addData">新增</el-button>
<!--            <el-button-->
<!--                type="primary"-->
<!--                plain-->
<!--                icon="CirclePlus"-->
<!--                size="mini"-->
<!--                @click="$refs.fileInput.click(ancestors)"-->
<!--            >-->
<!--                导入 Excel-->
<!--            </el-button>-->
            <input
                ref="fileInput"
                type="file"
                style="display: none"
                @change="handleFileUpload"
            />
          <el-button
              type="info"
              plain
              icon="Upload"
              @click="handleImport"
              v-hasPermi="['system:table:import']"
          >导入</el-button>
          <el-button
              type="primary"
              plain
              icon="el-icon-upload"
              size="mini"
              @click="toDetails()"
          >
            查看详细数据
          </el-button>
        </el-form-item>
        <el-table ref="multipleTableRef" v-loading="loading" :data="dataList"
                  @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center"/>
            <el-table-column label="id" align="left" prop="id" :show-overflow-tooltip="true"/>
            <el-table-column label="名称" align="left" prop="name" :show-overflow-tooltip="true"/>
            <el-table-column label="操作" align="center" prop="grade">
                <template #default="scope">
                    <el-button icon="CirclePlus" link type="primary" @click="addStudent(scope.row)">
                        添加
                    </el-button>

                </template>

            </el-table-column>
        </el-table>


    </el-form>
        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
                    v-model:limit="queryParams.pageSize" @pagination="handleQueryStu"/>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="beforeChoose">关 闭</el-button>
                </div>
            </template>
        </el-dialog>
      <!-- 数据导入对话框 -->
      <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
        <el-upload
            ref="uploadRef"
            :limit="1"
            accept=".xlsx, .xls"
            :headers="upload.headers"
            :action="upload.url + '?updateSupport=' + upload.updateSupport"
            :disabled="upload.isUploading"
            :file-list="uploadFiles"
            :on-change="loadJsonFromFile"
            :on-progress="handleFileUploadProgress"
            :on-success="handleFileSuccess"
            :auto-upload="false"
            drag
        >
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <template #tip>
            <div class="el-upload__tip text-center">
              <div class="el-upload__tip">
                <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据
              </div>
              <span>仅允许导入xls、xlsx格式文件。</span>
              <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
            </div>
          </template>
        </el-upload>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="submitFileForm">确 定</el-button>
            <el-button @click="upload.open = false">取 消</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
</template>


<script setup>

import {getCurrentInstance, reactive, ref} from "vue";
import {getDataById, importDataList} from "@/api/shenji/table";
import { useDetailsStore } from "@/store/modules/details";
import * as XLSX from "xlsx";
import {getToken} from "@/utils/auth";
const { proxy } = getCurrentInstance();
let uploadFiles = [];
const dataOpen = ref(false)
const dataTitle = ref('数据')
const total = ref(0)
const multiple = ref(true)
const ids = ref([])
const loading=ref(false)
const dataList=ref([])
const id=ref()
const nodeData = ref()
const store = useDetailsStore();
const queryParams = ref({
    pageNum: 1,
    pageSize: 10,
    name:null
})
/*** 用户导入参数 */
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/system/user/importData"
});

const toDetails = () =>{
  proxy.$router.replace({ name:'details' , params: { id: nodeData.value.id }});
}
const handleQueryStu=()=>{
    console.log("8888")
}

const beforeChoose = () => {
    dataOpen.value = false
    // getList()
}


function handleSelectionChange(selection) {
    ids.value = selection.map((item) => item.id)
    multiple.value = !selection.length
}

const init = (row) => {
    dataOpen.value=true
    store.updateRow(row);

    id.value=row.id
    getDataById(id.value).then(res=>{
        console.log("333",res)
        dataList.value=res.data;
        store.updateKeyList(dataList.value);
    })
    console.log("222",row)
    nodeData.value = row;
}
/** 导入按钮操作 */
function handleImport() {
  upload.title = "用户导入";
  upload.open = true;
};
/** 下载模板操作 */
function importTemplate() {
  proxy.download("system/user/importTemplate", {
  }, `user_template_${new Date().getTime()}.xlsx`);
};
/** 文件发生变化 */
const loadJsonFromFile = (file, fileList) =>{

  uploadFiles = fileList;
  console.log("uploadFiles;{}",uploadFiles)
}
/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  console.log("fileList;{}",fileList)
  upload.isUploading = true;
};
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  console.log("fileLis",fileList)
  upload.open = false;
  upload.isUploading = false;
  let myFile = uploadFiles[0];
  const reader = new FileReader();
  reader.readAsArrayBuffer(myFile.raw); // 使用 readAsArrayBuffer 读取 Excel 文件
  reader.onload = (e) => {
// 读取文件内容
    const bufferArray = e.target.result;

    // 将文件内容解析为 Workbook 对象
    const workbook = XLSX.read(bufferArray, { type: 'array' });
    // const data = new Uint8Array(e.target.result);
    // const workbook = XLSX.read(data, { type: "array" });
    //
    const firstSheetName = workbook.SheetNames[0];
    const worksheet = workbook.Sheets[firstSheetName];

    let excelData = XLSX.utils.sheet_to_json(worksheet, { raw: true });
    console.log("workbook",workbook);
    excelData[0].tableId = nodeData.value.id;
    console.log("excelData",excelData);
    importDataList(excelData)
        .then((response) => {
          // 处理上传成功后的响应
          console.log(response);
          proxy.$modal.msgSuccess("导入成功");
          init(nodeData.value);
        })
        .catch((error) => {
          // 处理上传失败后的错误
          console.error(error);
          proxy.$modal.msgSuccess("导入失败");
        });
  };
  proxy.$refs["uploadRef"].handleRemove(file);

  // getList();
};
/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
};

/** 主动暴露方法 */
defineExpose({init})

</script>



<style scoped lang="scss">

</style>
